package com.hmdp.service.impl;

import cn.hutool.Hutool;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 更新数据库
     * @param shop
     * @return
     */
    @Override
    public Result update(Shop shop) {
        Long id = shop.getId();
        if(id == null){
            return Result.fail("店铺id不能为空");
        }
        // 1.更新数据库
        updateById(shop);
        // 2.删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1 判断 带不带x,y 带 附近商户； 不带 正常分页查询
        if(x == null || y == null){
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        // 从redis中查询geo数据，以x,y为中心，半径5000m查询所有商铺信息，并且分页 from=(current-1)*size;end=current*size;
        int from = (current-1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
        );
        // 手动分页，并判断分页后是否还有数据
        if(results == null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        // 没有下一页
        if(from > list.size()){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> map = new HashMap<>(list.size());
        list.stream().skip(from).forEach(r -> {
            // 获取店铺id
            String idStr = r.getContent().getName();
            // 获取distance
            Distance distance = r.getDistance();
            // 对应
            ids.add(Long.valueOf(idStr));
            map.put(idStr, distance);
        });
        // 利用id查询shop信息，并把distance写进shop中
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id, " + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(map.get(shop.getId().toString()).getValue());
        }
        // 返回数据
        return Result.ok(shops);
    }


    /**
     * 根据id查询商铺信息
     * @param id
     * @return
     */
    public Result queryById(Long id){
        // 1.缓存穿透
//        Shop shop = cacheClient.queryWithPassThrough(
//                CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        // 2.互斥锁缓存击穿
//        Shop shop = queryWithMutex(id);

        // 3.逻辑过期解决缓存击穿
        Shop shop = cacheClient.queryWithLogicalExpire(
                CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_LOGICAL_TTL, TimeUnit.MINUTES);
        if(shop == null){
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    // 互斥锁
    /**
    private Shop queryWithMutex(Long id) {
        // 1.在Redis中查询商铺信息
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 2.存在，返回商铺信息
        if (StrUtil.isNotBlank(shopJson)) {
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        // 3.判断命中的是否是空值""
        if (shopJson != null) {
            return null;
        }
        // 4.不存在，在数据库中查询
        // 4.1 尝试获取互斥锁
        Shop shop;
        try {
            String lockKey = LOCK_SHOP_KEY + id;
            boolean isLock = tryLock(lockKey);
            if (!isLock) {
                // 4.2 没获取到，休眠一段时间，再重复
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            // 4.3 获取到锁，先查询缓存中是否有需要的数据，有就返回
            shopJson = stringRedisTemplate.opsForValue().get(key);
            // 存在，返回商铺信息
            if (StrUtil.isNotBlank(shopJson)) {
                return JSONUtil.toBean(shopJson, Shop.class);
            }
            // 判断命中的是否是空值""
            if (shopJson != null) {
                return null;
            }
            // 4.4 缓存中没有数据，在数据库中查询数据
            shop = getById(id);
            // 4.5 数据库中不存在，在redis中存入空值，返回错误信息  缓存穿透--缓存空值
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            // 4.6 存在，存储商铺信息到Redis中
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL + RandomUtil.randomLong(0, 10), TimeUnit.MINUTES);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 6. 释放锁
            unLock(LOCK_SHOP_KEY + id);
        }
        // 5.返回商铺信息
        return shop;
    }
     **/

    // 逻辑过期
    /**
    private Shop queryWithLogicalExpire(Long id) {
        // 1.在Redis中查询商铺信息
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 2.未命中，返回空
        if (StrUtil.isBlank(shopJson)) {
            return null;
        }
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        // 3.命中，判断逻辑是否过期
        // 3.1 未过期，返回数据
        Shop shop = BeanUtil.toBean(redisData.getData(),Shop.class);
        if (redisData.getExpireTime().isAfter(LocalDateTime.now())){
            return shop;
        }
        // 4.过期,重建缓存
        // 4.1 尝试获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if (isLock) {
            // 4.2 获取到锁，开启独立线程
            // DoubleCheck 缓存是否过期
            String shopJson2 = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isBlank(shopJson2)) {
                return null;
            }
            RedisData redisData2 = JSONUtil.toBean(shopJson, RedisData.class);
            Shop shop2 = BeanUtil.toBean(redisData.getData(),Shop.class);
            if (redisData2.getExpireTime().isAfter(LocalDateTime.now())){
                return shop2;
            }
            // 开启独立线程
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    // 4.3 独立线程更新缓存
                    this.save2RedisData(id,20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    // 释放锁
                    unLock(lockKey);
                }
            });
        }
        // 4.4 没获取到锁，返回旧数据
        return shop;
    }**/

    // 缓存空值解决缓存穿透
    /**
    private Shop queryWithPassThrough(Long id) {
        // 1.在Redis中查询商铺信息
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 2.存在，返回商铺信息
        if(StrUtil.isNotBlank(shopJson)){
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        // 3.判断命中的是否是空值""
        if(shopJson != null){
            return null;
        }
        // 4.不存在，在数据库中查询
        Shop shop = getById(id);
        // 5.不存在，在redis中存入空值，返回错误信息  缓存穿透--缓存空值
        if(shop == null){
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        // 6.存在，存储商铺信息到Redis中
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL+ RandomUtil.randomLong(0,10), TimeUnit.MINUTES);
        // 7.返回商铺信息
        return shop;
    }
     **/

    // 获取锁
    /**
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key,"1",10,TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
     **/
    // 释放锁
    /**
    private void unLock(String key){
        Boolean flag = stringRedisTemplate.delete(key);
    }
     **/

    // 将商铺数据写入Redis并设置逻辑过期时间
    public Shop save2RedisData(Long id, Long expireTime){
        Shop shop = getById(id);
        try {
            // 模拟缓存延迟
            Thread.sleep(200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
        return shop;
    }
}
